package com.flashcash.solu.app.base;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flashcash.solu.R;
import com.flashcash.solu.app.base.presenter.BaseFragmentPresenter;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.utils.NotificationUtils;
import com.flashcash.solu.view.MsgBoxActivity;
import com.flashcash.solu.widget.XLeoSp;
import com.trello.rxlifecycle.LifecycleProvider;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.RxLifecycle;
import com.trello.rxlifecycle.android.FragmentEvent;
import com.trello.rxlifecycle.android.RxLifecycleAndroid;
import com.x.leo.apphelper.log.XLog;

import java.lang.reflect.Field;

import javax.annotation.Nonnull;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Optional;
import butterknife.Unbinder;
import rx.Observable;
import rx.subjects.BehaviorSubject;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * Created by Administrator on 2016/5/31 0031.
 * <p>
 * 基类fragment
 *
 * @author tj
 */
public abstract class BaseFragment<T extends BaseFragmentPresenter> extends Fragment implements
        BaseFragmentView, LifecycleProvider<FragmentEvent> {
    @BindView(R.id.id_imagebutton_back)
    @Nullable
    ImageButton idImagebuttonBack;
    @BindView(R.id.id_textview_title)
    @Nullable
    TextView idTextviewTitle;
    @BindView(R.id.id_imagebutton_info_list)
    @Nullable
    ImageButton idImagebuttonInfoList;
    @BindView(R.id.id_main_top)
    @Nullable
    LinearLayout idMainTop;
    @Nullable
    LinearLayout llFragmentBase;
    private Unbinder unbinder;
    protected BaseActivity mActivity;
    protected LayoutInflater inflater;

    protected T mPresenter;

    private final BehaviorSubject<FragmentEvent> lifecycleSubject = BehaviorSubject.create();

    @Override
    public BaseActivity getBaseActivity() {
        return mActivity;
    }


    protected abstract T initPresenter();

    /**
     * 获得全局的，防止使用getActivity()为空
     *
     * @param context system
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.lifecycleSubject.onNext(FragmentEvent.ATTACH);
        this.mActivity = (BaseActivity) getActivity();
    }

    @Override
    public void onDetach() {
        this.lifecycleSubject.onNext(FragmentEvent.DETACH);
        hideSoftSpan();
        super.onDetach();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.lifecycleSubject.onNext(FragmentEvent.CREATE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getBaseActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Nullable
    @Optional
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container
            , Bundle savedInstanceState) {
        this.lifecycleSubject.onNext(FragmentEvent.CREATE_VIEW);
        mPresenter = initPresenter();
        mPresenter.attach(this);
        this.inflater = inflater;

        View rootView;
        View view = LayoutInflater.from(mActivity)
                .inflate(getLayoutId(), container, false);
        if (doPreBuildHeader()) {
            rootView = LayoutInflater.from(mActivity).inflate(R.layout.fragment_base, container,
                    false);
            llFragmentBase = rootView.findViewById(R.id.ll_fragment_base);
            if (llFragmentBase != null) {
                llFragmentBase.addView(view, new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                        .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            } else {
                rootView = view;
            }
        } else {
            rootView = view;
        }
        unbinder = ButterKnife.bind(this, rootView);
        if (doPreBuildHeader()) {
            if (!initHeader(idTextviewTitle)) {
                if (idImagebuttonInfoList != null)
                    idImagebuttonInfoList.setVisibility(View.INVISIBLE);
            } else {
                if (idImagebuttonInfoList != null) {
                    idImagebuttonInfoList.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            idImagebuttonInfoList.setActivated(false);
                            XLeoSp.getInstance(mActivity).remove(FieldParams.PageStatus
                                    .HAS_NEW_MESSAGE);
                            Intent intent = new Intent(mActivity, MsgBoxActivity.class);
                            startActivity(intent);
                        }
                    });
                    initPageStatus();
                }
            }
            if (idImagebuttonBack != null) {
                if (getBackPressListener() != null) {
                    idImagebuttonBack.setOnClickListener(getBackPressListener());
                } else {
                    idImagebuttonBack.setVisibility(View.INVISIBLE);
                    idImagebuttonBack.setVisibility(showBack() ? View.VISIBLE : View.INVISIBLE);
                }

            }
            //设置标题
            if (!TextUtils.isEmpty(getTitle())) {
                idTextviewTitle.setText(getTitle());
            }
            //设置是否显示系统消息图标
            idImagebuttonInfoList.setVisibility(showMessageIcon() ? View.VISIBLE : View.INVISIBLE);
        }
        /*if (idTextviewTitle != null && idImagebuttonBack != null) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) idTextviewTitle.getLayoutParams();

            if (idImagebuttonBack.getVisibility() != View.VISIBLE) {
//                Drawable drawable = ContextCompat.getDrawable(mActivity, R.drawable
//                        .ic_toolbar_logo);
//                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                idTextviewTitle.setCompoundDrawables(drawable, null, null, null);

                layoutParams.leftMargin = (int) mActivity.getResources().getDimension(R.dimen.dp10);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                layoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.id_imagebutton_back);
                idTextviewTitle.setLayoutParams(layoutParams);
            } else {
                idTextviewTitle.setCompoundDrawables(null, null, null, null);

                layoutParams.leftMargin = (int) mActivity.getResources().getDimension(R.dimen.dp01);
                layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                layoutParams.addRule(RelativeLayout.RIGHT_OF, R.id.id_imagebutton_back);
                idTextviewTitle.setLayoutParams(layoutParams);
            }
        }*/
        initView(rootView, savedInstanceState);
        initData();

        //监听第一次显示

        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        this.lifecycleSubject.onNext(FragmentEvent.START);
    }

    @Override
    public void onResume() {
        super.onResume();
        this.lifecycleSubject.onNext(FragmentEvent.RESUME);
    }

    @Override
    public void onPause() {
        this.lifecycleSubject.onNext(FragmentEvent.PAUSE);
        super.onPause();
    }

    @Override
    public void onStop() {
        this.lifecycleSubject.onNext(FragmentEvent.STOP);
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        this.lifecycleSubject.onNext(FragmentEvent.DESTROY_VIEW);
        super.onDestroyView();
        unbinder.unbind();
        mPresenter.detach();
        mPresenter = null;
    }

    @Override
    public void onDestroy() {
        this.lifecycleSubject.onNext(FragmentEvent.DESTROY);
        super.onDestroy();
    }

    @Optional
    public void informMessage() {
        infoMessageCallBack();
        if (idImagebuttonInfoList != null) {
            idImagebuttonInfoList.setActivated(true);
        }
        Intent intent = new Intent(mActivity, MsgBoxActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mActivity, 0, intent, 0);
        NotificationUtils.showNotificationHasPendingIntent(mActivity, "New Message", "New Loan Information", R.drawable.ic_chat, pendingIntent);
    }

    /**
     * 提供给ProductFragment实现的方法
     */
    protected void infoMessageCallBack() {

    }

    /**
     * 设置标题
     *
     * @return
     */
    protected String getTitle() {
        return "";
    }

    /**
     * 是否显示系统消息图标
     *
     * @return
     */
    protected boolean showMessageIcon() {
        return true;
    }

    /**
     * 是否拥有返回
     *
     * @return
     */
    protected boolean showBack() {
        return false;
    }

    @Optional
    private void initPageStatus() {
        if (idImagebuttonInfoList != null) {
            boolean aBoolean = XLeoSp.getInstance(mActivity).getBoolean(FieldParams.PageStatus
                    .HAS_NEW_MESSAGE);
            idImagebuttonInfoList.setActivated(aBoolean);
        }
    }

    /**
     * set back button OnClickListener
     *
     * @return Onclicklistener or null present no back button default no back button
     */
    protected View.OnClickListener getBackPressListener() {
        return null;
    }

    /**
     * @param view header to set
     * @return has info icon or not
     */
    protected boolean initHeader(TextView view) {
        view.setText(R.string.app_name);
        return true;
    }

    @Override
    public void toLogin() {
        if (mActivity != null) {
            mActivity.toLogin();
        }
    }

    // LifeCycleProvider overrides
    @Nonnull
    @Override
    public Observable<FragmentEvent> lifecycle() {
        return this.lifecycleSubject.asObservable();
    }

    @Nonnull
    @Override
    public <X> LifecycleTransformer<X> bindUntilEvent(@Nonnull FragmentEvent event) {
        return RxLifecycle.bindUntilEvent(this.lifecycleSubject, event);
    }

    @Nonnull
    @Override
    public <X> LifecycleTransformer<X> bindToLifecycle() {
        return RxLifecycleAndroid.bindFragment(this.lifecycleSubject);
    }

    /**
     * @return prebuildHeader or not
     */
    protected boolean doPreBuildHeader() {
        return false;
    }

    /**
     * 该抽象方法就是 onCreateView中需要的layoutID
     *
     * @return 布局id
     */
    protected abstract int getLayoutId();

    /**
     * 该抽象方法就是 初始化view
     *
     * @param view               onCreatedView‘s view
     * @param savedInstanceState saveInstanceState
     */
    protected abstract void initView(View view, Bundle savedInstanceState);

    /**
     * 执行数据的加载
     */
    protected abstract void initData();

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            hideSoftSpan();
        } else {
        }
        super.onHiddenChanged(hidden);
    }

    private void hideSoftSpan() {
        try {
            if (getContext() == null) {
                return;
            }
            InputMethodManager imm = (InputMethodManager) getContext().getSystemService
                    (INPUT_METHOD_SERVICE);
            if (imm == null) {
                return;
            }
            String[] arr = new String[]{"mServedView", "mNextServedView", "mCurRootView"};
            Field f;
            Object obj_get;
            for (String param : arr) {
                f = imm.getClass().getDeclaredField(param);
                if (f == null) {
                    continue;
                }
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    imm.hideSoftInputFromWindow(v_get.getWindowToken(), 0);
                }
            }
        } catch (Exception e) {
            XLog.INSTANCE.e("hide soft span error:" + e.getMessage(), e, 100);
        }
    }

}